package com.legutech.gsyvideoplayer.gsy_video_player;

import android.content.Context;
import android.media.AudioManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.legutech.gsyvideoplayer.gsy_video_player.utils.CustomManager;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge;

/**
 * @author 作者： hfjs
 * @desc 描述：
 * @time 创建时间：2018/12/11 10:01
 * @change_time 修改时间：
 * @change_desc 修改原因：
 */
public class RealVideo extends StandardGSYVideoPlayer implements NeedMutesObserver {
    private String TAG;
    private ProgressBar mProgressBar;
    private TextView mCodeType, mMoreScale;
    private ImageView mMoreVoice;
    // 记住切换数据源类型
    private int mType = 0;
    private int mCode = 1;
    private boolean isNeedMute = true;// 是否静音

    public RealVideo(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public RealVideo(Context context) {
        super(context);
    }

    public RealVideo(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        setVideoView();
        onAudioFocusChangeListener = focusChange -> {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
            }
        };

    }

    private void setVideoView() {
        mProgressBar = findViewById(R.id.loading_progress);
        mCodeType = findViewById(R.id.code_type);
        mMoreVoice = findViewById(R.id.more_voice);
        mMoreVoice.setSelected(false);
        mMoreScale = findViewById(R.id.more_scale);
        CustomManager.getCustomManager(getKey()).setNeedMutes(true);

        // 切换清晰度
        mMoreScale.setOnClickListener(v -> {
            if (!mHadPlay) {
                return;
            }
            if (mType == 0) {
                mType = 1;
            } else if (mType == 1) {
                mType = 2;
            } else if (mType == 2) {
                mType = 3;
            } else if (mType == 3) {
                mType = 0;
            }
            resolveTypeUI();
        });
        mCodeType.setOnClickListener(v -> {
            if (!mHadPlay) {
                return;
            }
            if (mCode == 0) {
                mCode = 1;
            } else if (mCode == 1) {
                mCode = 0;
            }
            resolveCodeUI();
            if (listener != null)
                listener.onClick(mCode);
        });
        mMoreVoice.setOnClickListener(v -> {
            if (!mHadPlay) {
                return;
            }
            NeedMutesUtil.getInstance().setAudioState(getKey(), isNeedMute);
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_real_video;
    }

    @Override
    protected void touchSurfaceMove(float deltaX, float deltaY, float y) {
    }

    @Override
    protected void updateStartImage() {
        if (mStartButton instanceof ImageView) {
            ImageView imageView = (ImageView) mStartButton;
            if (mCurrentState == CURRENT_STATE_PLAYING) {
                imageView.setImageResource(R.mipmap.video_pause_pressed);
            } else if (mCurrentState == CURRENT_STATE_ERROR) {
                imageView.setImageResource(R.mipmap.video_play_normal);
            } else {
                imageView.setImageResource(R.mipmap.video_play_normal);
            }
        }
    }

    public void setProgressState(boolean isShow) {
        if (isShow) {
            mProgressBar.setVisibility(VISIBLE);
            mStartButton.setVisibility(GONE);
        } else {
            mProgressBar.setVisibility(GONE);
        }
    }

    /**
     * 显示比例
     * 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。
     */
    private void resolveTypeUI() {
        if (!mHadPlay) {
            return;
        }
        if (mType == 1) {
            mMoreScale.setText("16:9");
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9);
        } else if (mType == 2) {
            mMoreScale.setText("4:3");
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3);
        } else if (mType == 3) {
            mMoreScale.setText(R.string.desc_full_screen);
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL);
        } else if (mType == 0) {
            mMoreScale.setText(R.string.desc_default_ratio);
            GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT);
        }
        changeTextureViewShowType();
        if (mTextureView != null)
            mTextureView.requestLayout();
    }

    private void resolveCodeUI() {
        if (!mHadPlay) {
            return;
        }
        if (mCode == 0) {
            mCodeType.setText(mContext.getString(R.string.desc_main_stream));
        } else if (mCode == 1) {
            mCodeType.setText(mContext.getString(R.string.desc_sub_stream));
        }
    }

    private void resolveVoiceUI() {
        if (!mHadPlay) {
            return;
        }
        mMoreVoice.setSelected(!isNeedMute);
    }

    /**
     * 设置声音状态
     */
    public void setNeedMute() {
        NeedMutesUtil.getInstance().attachObserver(getKey(), this);
        CustomManager.getCustomManager(getKey()).setNeedMutes(isNeedMute);
    }

    /**
     * 全屏时将对应处理参数逻辑赋给全屏播放器
     *
     * @param context
     * @param actionBar
     * @param statusBar
     * @return
     */
    @Override
    public GSYBaseVideoPlayer startWindowFullscreen(Context context, boolean actionBar, boolean statusBar) {
        RealVideo customVideo = (RealVideo) super.startWindowFullscreen(context, actionBar, statusBar);
        customVideo.mType = mType;
        customVideo.mCode = mCode;
        customVideo.isNeedMute = isNeedMute;
        customVideo.resolveTypeUI();
        customVideo.resolveCodeUI();
        customVideo.resolveVoiceUI();
        return customVideo;
    }

    @Override
    protected void cloneParams(GSYBaseVideoPlayer from, GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        RealVideo sf = (RealVideo) from;
        RealVideo st = (RealVideo) to;
        st.listener = sf.listener;
    }

    /**
     * 推出全屏时将对应处理参数逻辑返回给非播放器
     *
     * @param oldF
     * @param vp
     * @param gsyVideoPlayer
     */
    @Override
    protected void resolveNormalVideoShow(View oldF, ViewGroup vp, GSYVideoPlayer gsyVideoPlayer) {
        super.resolveNormalVideoShow(oldF, vp, gsyVideoPlayer);
        if (gsyVideoPlayer != null) {
            RealVideo sampleVideo = (RealVideo) gsyVideoPlayer;
            mType = sampleVideo.mType;
            mCode = sampleVideo.mCode;
            isNeedMute = sampleVideo.isNeedMute;
            resolveTypeUI();
            resolveCodeUI();
            resolveVoiceUI();
        }
    }

    private OnVideoClickListener listener;

    public void setOnVideoClickListener(OnVideoClickListener listener) {
        this.listener = listener;
    }

    @Override
    public void changeNeedMutes(boolean isNeedMutes) {
        if (!mHadPlay) {
            return;
        }
        isNeedMute = isNeedMutes;
        mMoreVoice.setSelected(!isNeedMutes);
        CustomManager.getCustomManager(getKey()).setNeedMutes(isNeedMutes);
    }

    public interface OnVideoClickListener {
        void onClick(int codeType);
    }

    @Override
    public GSYVideoViewBridge getGSYVideoManager() {
        CustomManager.getCustomManager(getKey()).initContext(getContext().getApplicationContext());
        return CustomManager.getCustomManager(getKey());
    }

    @Override
    protected boolean backFromFull(Context context) {
        return CustomManager.backFromWindowFull(context, getKey());
    }

    @Override
    protected void releaseVideos() {
        NeedMutesUtil.getInstance().detachObserver(getKey());
        CustomManager.releaseAllVideos(getKey());
    }

    @Override
    protected int getFullId() {
        return CustomManager.FULLSCREEN_ID;
    }

    @Override
    protected int getSmallId() {
        return CustomManager.SMALL_ID;
    }

    public String getKey() {
        if (mPlayPosition == -22) {
            Debuger.printfError(
                    getClass().getSimpleName() + " used getKey() " + "******* PlayPosition never set. ********");
        }
        if (TextUtils.isEmpty(mPlayTag)) {
            Debuger.printfError(getClass().getSimpleName() + " used getKey() " + "******* PlayTag never set. ********");
        }
        return TAG + mPlayPosition + mPlayTag;
    }

}
